// 文件 I/O 与网络测试
// src/io.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "io.h"

void io_test() {
    // 文件 I/O
    const char *fname = "io_test.txt";
    int fd = open(fname, O_CREAT | O_RDWR, 0644);
    if (fd < 0) {
        perror("open");
        return;
    }
    const char *msg = "Hello file I/O\n";
    write(fd, msg, strlen(msg));
    lseek(fd, 0, SEEK_SET);
    char buf[64];
    int n = read(fd, buf, sizeof(buf)-1);
    if (n > 0) {
        buf[n] = '\0';
        printf("Read from file: %s", buf);
    }
    close(fd);

    // UDP 网络 I/O
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket");
        return;
    }
    struct sockaddr_in dest = {0};
    dest.sin_family = AF_INET;
    dest.sin_port   = htons(9999);
    inet_aton("127.0.0.1", &dest.sin_addr);
    const char *netmsg = "Hello network I/O";
    sendto(sock, netmsg, strlen(netmsg), 0,
           (struct sockaddr*)&dest, sizeof(dest));
    printf("UDP packet sent to 127.0.0.1:9999\n");
    close(sock);
}
